<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <title></title>
    <link href="css/mui.min.css" rel="stylesheet"/>
    <link rel="stylesheet" type="text/css" href="css/header.css"/>
    <link rel="stylesheet" type="text/css" href="css/chat.css"/>
    <style>
        html,
        body {
            height: 100%;
            margin: 0px;
            padding: 0px;
            overflow: hidden;
            -webkit-touch-callout: none;
            -webkit-user-select: none;
        }
    </style>
</head>

<body contextmenu="return false;">

<header class="mui-bar mui-bar-nav title" style="position: fixed;">
    <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left title-color"></a>
    <h1 class="mui-title title-color"><b id="chatting-nickname">微 信</b></h1>
</header>

<div id="msg-outter" class="mui-content">
    <div id='msg'>


    </div>
</div>

<footer>
    <div class="footer-center">
        <textarea id='msg_text' type="text" class='input-text'></textarea>
    </div>
    <label for="" class="footer-right">
        <button type="button" class="mui-btn mui-btn-gray" id="send">发送</button>
    </label>
</footer>

<script src="js/mui.min.js"></script>
<script type="application/javascript" src="js/app.js"></script>
<script type="text/javascript">

    var friendUserId;
    var friendNickname;
    var friendFaceImage;

    mui.plusReady(function () {


        //获取自己的缓存信息
        var myInfo = app.getUserGlobalInfo();
        //获取连天页面webview
        var chatWebView = plus.webview.currentWebview();
        //设置聊天页面的软键盘样式
        chatWebView.setStyle({
            softinputMode: "adjustResize"
        });
        //获取上个页面传入的值
        friendUserId = chatWebView.friendUserId;
        friendNickname = chatWebView.friendNickname;
        friendFaceImage = chatWebView.friendFaceImage;
        //修改标题栏为昵称
        var chatting_nickname = document.getElementById("chatting-nickname");
        chatting_nickname.innerText = friendNickname;
        //从缓存中获取聊天记录并渲染
        initChatHistory();
        //设置滚动条到底部
        resizeScreen();
        //获取是否是有未读消息 如果是则改为已读并重新渲染
        isNotRead(myInfo.id,friendUserId);
        
        //获取发送按钮
        var msg_text = document.getElementById("msg_text");
        var send = document.getElementById("send");
        msg_text.addEventListener("input", function () {
            //根据内容变换输入按钮样式
            if ((swap = msg_text.value).replace(/^\s*/, "").length > 0) {
                //设置滚动条到底部
                send.setAttribute("class", "mui-btn-green");
            } else {
                send.setAttribute("class", "mui-btn-gray");
            }
        });

        /*//添加自定义事件,刷新头像,退出时调用
        window.addEventListener("showGetedData", function () {
            showGetedData();
        });*/

        //半屏后消息滚动到底部
        window.addEventListener("resize", function () {
            resizeScreen();
            //展示被遮盖的最后一条消息
            var msg_outter = document.getElementById("msg-outter");
            msg_outter.style.paddingBottom = "50px";
        });

        //发送消息的按钮事件绑定
        send.addEventListener("tap", function () {
            //发送之前判断网络状态
            var networkinfo = plus.networkinfo.getCurrentType();
            console.log("当前网络状态 : " + networkinfo);
            if (networkinfo == 0 || networkinfo == 1) {
                app.showToast("请打开网络连接", "error");
                return false;
            } else {
                //获取消息内容
                var content = msg_text.value;
                //校验内容
                if ((swap = content).replace(/^\s*/, "").length == 0) {
                    app.showToast("不能发送空消息", "error");
                    return false;
                } else {

                    //构建chatMsg
                    var chatMsg = new app.ChatMsg(myInfo.id, friendUserId, content, null);
                    //构建dataContent
                    var dataContent = new app.DataContent(app.CHAT, chatMsg, null);

                    //发送消息到websocket服务器
                    sendMsgToWebSocket(JSON.stringify(dataContent));

                    //发送消息
                    sendMsg(myInfo.faceImage, content);

                    //清空输入框内容
                    dropMessageInputContent();

                    //保存聊天记录到缓存
                    app.saveUserChatHistory(myInfo.id, friendUserId, content, 1,true,null);

                    //保存聊天快照
                    app.saveUserChatSnapshot(myInfo.id,friendUserId,content,true);
                }
            }
        });
    });

    //是否有未读消息 如果有则更改为已读并重新渲染
    function isNotRead(myId,friendUserId){
        console.log("检查是否有未读消息 如果有则更改为已读并重新渲染");
        //获取聊天快照
        var chatSnapshotList = app.getUserChatSnapshot(myId);
        for (var i=0;i<chatSnapshotList.length;i++){
            chatSnapshot = chatSnapshotList[i];
            console.log("检查 chatSnapshot对象" + JSON.stringify(chatSnapshot));
            //判断id是否一致
            if (chatSnapshot.friendId===friendUserId) {
                //是否是未读
                if (chatSnapshot.isRead===false){
                    console.log("有未读消息 开始改为已读消息 并刷新重新加载快照 "+JSON.stringify(chatSnapshot));
                    chatSnapshotList[i].isRead=true;
                    //重新设置聊天快照列表
                    app.saveChatSnapshot(myId,chatSnapshotList);
                    //发送重新刷新列表事件
                    var myfaceWebview = plus.webview.getWebviewById("chart-List.html");
                    mui.fire(myfaceWebview, "reloadChatSnapshot");
                    //签收未签收的消息
                    checkHaveNotReadChatHistory(myId,friendUserId);
                }else{
                    console.log("朋友id不一致");
                }
            }else{
                console.log("firendId不一致 开始下一个");
            }
        }  
    }

    //检查是否有未签收的聊天记录
    function checkHaveNotReadChatHistory(myId,friendUserId) {
        console.log("************************开始准备签收所有未读信息******************************");
        //获取缓存中的聊天记录
        var chatHistoryList = app.getUserChatHistory(myId,friendUserId);
        console.log("************************缓存中聊天记录获取完毕******************************"+JSON.stringify(chatHistoryList));
        if (chatHistoryList!=null){
            //存放未签收id
            var ids = "";
            for (var i = 0;i<chatHistoryList.length;i++){
                chatHistory = chatHistoryList[i];
                //是不是朋友发送的
                if (chatHistory.flag==2){
                    //是不是未读
                    if (chatHistory.isRead!=null&&chatHistory.msgId!=null&&chatHistory.isRead==false){
                        if (app.isNotNull(ids)){
                            ids+=",";
                        }
                        ids+=chatHistory.msgId;
                    }
                }
            }

            if (app.isNotNull(ids)){
                //构建dataContent
                var dataContent = new app.DataContent(app.SIGNED, null, ids);
                console.log("************************开始发送websocket签收信息到服务器******************************"+JSON.stringify(dataContent));
                //发送消息到websocket服务器
                sendMsgToWebSocket(JSON.stringify(dataContent));
            }

        }

    }
    
    //发送消息到websocket服务器
    function sendMsgToWebSocket(msg) {
        //首先触发自定义事件初始化与服务器的链接
        var chart_List = plus.webview.getWebviewById("chart-List.html");
        mui.fire(chart_List, "openWebSocket");

        //获取chart list 的webview 发送消息
        var webSocketWebView = plus.webview.getWebviewById("chart-List.html");
        webSocketWebView.evalJS("CHAT.chat('" + msg + "')");
    }

    //清空聊天输入框内容
    function dropMessageInputContent() {
        var msg_text = document.getElementById("msg_text");
        msg_text.value = "";
    }

    //播放接受到消息的铃声
    function playGetedMsgSound() {
        var audioPlayer = plus.audio.createPlayer("/mp3/di_didi.mp3");
        audioPlayer.play();
    }

    //播放发送到消息的铃声
    function playsendMsgSound() {
        var audioPlayer = plus.audio.createPlayer("/mp3/send.mp3");
        audioPlayer.play();

    }

    //发送消息
    function sendMsg(faceImg, msg) {
        var sendFaceImage = app.imgServerUrl + faceImg;
        if (!app.isNotNull(faceImg)) {
            sendFaceImage = "image/face.jpeg"
        }
        var newMsg = '<div class="me_lists">' +
            '<div class="header_img">' +
            '<img src="' + sendFaceImage + '" width="40px" height="40px"/>' +
            ' </div>' +
            '<div class="msg-wrapper left">' +
            '<p class="msg-right-green">' + msg + '</p>' +
            '</div>' +
            '</div>';
        var msgShowHtml = document.getElementById("msg");
        msgShowHtml.insertAdjacentHTML("beforeend", newMsg);
        //发送消息的铃声
        playsendMsgSound();
        //重新把页面滚动到底部
        resizeScreen();
    }

    //接收消息
    function getMsg(msg) {
        var getFaceImage = app.imgServerUrl + friendFaceImage;
        if (!app.isNotNull(friendFaceImage)) {
            getFaceImage = "image/face.jpeg"
        }
        var newMsg = '<div class="friend_lists">' +
            '<div class="header_img">' +
            '<img src="' + getFaceImage + '" width="40px" height="40px"/>' +
            '</div>' +
            '<div class="msg-wrapper right">' +
            '<p class="msg-left-white">' + msg + '</p>' +
            '</div>' +
            '</div>';
        var msgShowHtml = document.getElementById("msg");
        msgShowHtml.insertAdjacentHTML("beforeend", newMsg);
        //比方收到消息的铃声
        playGetedMsgSound();
        //重新把页面滚动到底部
        resizeScreen();
    }

    //设置滚动条到底部
    function resizeScreen() {
        //设置滚动条到底部
        var msgList = document.getElementById("msg");
        msgList.scrollTop = msgList.scrollHeight + msgList.offsetHeight;
    }

    //从缓存中取聊天记录并初始化渲染
    function initChatHistory() {
        var msg = document.getElementById("msg");
        var myinfo = app.getUserGlobalInfo();
        var myId = myinfo.id;
        var myImg = myinfo.faceImage;

        //默认头像
        if (!app.isNotNull(myImg)) {
            myImg = "image/face.jpeg"
        }else{
            myImg = app.imgServerUrl+myImg;
        }
        var firendImg = friendFaceImage;
        if (!app.isNotNull(firendImg)) {
            firendImg = "image/face.jpeg"
        }else{
            firendImg = app.imgServerUrl+firendImg;
        }
        //获取缓存中的聊天记录
        var chatHistoryList = app.getUserChatHistory(myId, friendUserId);
        console.log("获取到本地缓存 : "+JSON.stringify(chatHistoryList));
        for (var i = 0; i < chatHistoryList.length; i++) {
            var chatHistory = chatHistoryList[i];
            console.log("遍历单挑本地缓存记录 : "+JSON.stringify(chatHistory));
            //我
            var newMsg = "";
            if (chatHistory.flag == 1) {
                newMsg = '<div class="me_lists">' +
                    '<div class="header_img">' +
                    '<img src="' + myImg + '" width="40px" height="40px"/>' +
                    ' </div>' +
                    '<div class="msg-wrapper left">' +
                    '<p class="msg-right-green">' + chatHistory.msg + '</p>' +
                    '</div>' +
                    '</div>';
                //朋友
            } else {
                newMsg = '<div class="friend_lists">' +
                    '<div class="header_img">' +
                    '<img src="' + firendImg + '" width="40px" height="40px"/>' +
                    '</div>' +
                    '<div class="msg-wrapper right">' +
                    '<p class="msg-left-white">' + chatHistory.msg + '</p>' +
                    '</div>' +
                    '</div>';
            }
            //添加元素
            msg.insertAdjacentHTML("beforeend", newMsg);
        }
    }

</script>
</body>

</html>